<template>
  <div :class="$style.skill">
    <Icon :allow="allow" :src="src" :srcset="srcset" :text="text" @on-click="iconClickHandle" />
    <el-dialog
      :visible.sync="visible"
      append-to-body
      :close-on-click-modal="false"
      title="选择技能队列"
      @open="openedHandle"
    >
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item prop="skillid" label="技能队列">
          <el-select
            v-model="formData.skillid"
            placeholder="请选择技能队列"
            clearable
            filterable
            multiple
            style="width:100%"
          >
            <el-option v-for="(s,i) in skillQueue" :key="i" :value="s.id" :label="s.name" />
          </el-select>
          <div :class="$style.btnSelect">
            <Button type="primary" @click="allSelectHandle">全选</Button>
            <Button type="primary" @click="reverseSelectHandle">反选</Button>
          </div>
        </el-form-item>
        <el-form-item>
          <div :class="$style.btn">
            <Button @click="visible=false">取消</Button>
            <Button type="primary" :loading="loading" @click="confirmHandle">确定</Button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import Icon from './Icon'
import beforeSign from './js/beforeSign.js'
import afterSign from './js/afterSign.js'
import { mapMutations, mapGetters, mapActions } from 'vuex'
export default {
  name: 'Skill',
  components: {
    Icon
  },
  data() {
    const validatorSelected = (r, v, c) => {
      if (v.length > 0) {
        c()
      } else {
        c(new Error('至少选择一项'))
      }
    }
    return {
      timerid: null, // 排队轮询定时器
      stop: false, // 是否停止轮询
      loading: false,
      visible: false,
      formData: {
        skillid: []
      },
      formRules: {
        skillid: [
          { required: true, validator: validatorSelected, trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['callInfo', 'agentState', 'interval', 'skillList', 'queueSize', 'agentid', 'phonenum', 'agentInfo']),
    ...mapGetters(['skillInfoList']),
    src() {
      return this.allow ? afterSign.skills : beforeSign.skills
    },
    srcset() {
      return this.allow ? afterSign.skills2x : beforeSign.skills2x
    },
    text() {
      return '技能'
    },
    allow() {
      // const { sign, talk } = this.agentState
      // return sign && !talk
      const { sign } = this.agentState
      return sign
    },
    skillQueue() {
      // return this.skillList // 华为平台获取的
      return this.skillInfoList // 当前登录账户的
    }
  },
  created() {
    // 监听签出时间，取消轮询
    this.$cps.on('OnSignOutSuccess', () => {
      clearTimeout(this.timerid)
      this.stop = true
    })
    this.$cps.on('OnSignInSuccess', () => {
      this.stop = false
    })
  },
  methods: {
    ...mapMutations(['SET_AGENT_INFO']),
    ...mapActions(['queryAgentInfoByWorkNo', 'queryTotalSkills', 'voiceSkillStatistic']),
    // 话务条被单击
    iconClickHandle() {
      if (!this.allow) {
        return
      } else {
        this.visible = true
      }
    },
    // 全选
    allSelectHandle() {
      this.$set(this.formData, 'skillid', [])
      for (const item of this.skillQueue) {
        this.formData.skillid.push(item.id)
      }
    },
    // 反选
    reverseSelectHandle() {
      const t = []
      const skillid = this.formData.skillid
      for (const item of this.skillQueue) {
        if (skillid.indexOf(item.id) === -1) {
          t.push(item.id)
        }
      }
      this.$set(this.formData, 'skillid', t)
    },
    // 弹窗后确认
    confirmHandle() {
      this.loading = true
      this.$refs.form
        .validate()
        .then(() => {
          const oldSkillIds = this.agentInfo && this.agentInfo.skilllist ? this.agentInfo.skilllist.map(e => this.$numToString(e.id)) : []
          return this.$cps.changeAgentSkill(false, this.formData.skillid.join(';'), 1).then(res => {
            this.$notifySuccess('修改技能队列成功！')
            this.queryAgentInfoByWorkNo(this.agentid).then(e => {
              const skillListIds = (e.data.skilllist || []).map(e => this.$numToString(e.id))
              this.skillOperatorLog(oldSkillIds, skillListIds)
              // if (skillListIds.length <= 0) {
              //   this.$callOperatorLogFail(10)
              // } else {
              // const names = []
              // for (const item of this.skillQueue) {
              //   if (skillList.includes(this.$numToString(item.id))) {
              //     names.push(item.name)
              //   }
              // }
              // this.$callOperatorLogSuccess(10, names.join(',')) // 签出成功
              // }
              if (this.timerid)clearTimeout(this.timerid)
              this.getQueueSize()
            })
            this.visible = false
          }).catch(() => {
            this.$callOperatorLogFail(10)
            this.$notifyError('修改技能队列失败！')
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 获取技能列表
    getKillList() {
      this.queryTotalSkills(this.agentid).catch(() => {
        this.$notifyError('获取技能队列失败！')
      })
    },
    openedHandle() {
      this.getKillList()
      // 设置已有的技能
      this.$set(this.formData, 'skillid', [])
      for (const item of this.agentInfo.skilllist) {
        this.formData.skillid.push(this.$numToString(item.id))
      }
    },
    // 获取排队人数
    getQueueSize() {
      clearTimeout(this.timerid)
      this.timerid = setTimeout(() => {
        this.voiceSkillStatistic().finally(() => {
          if (!this.stop) {
            this.getQueueSize()
          }
        })
      }, 600)
    },
    // 记录技能操作日志
    skillOperatorLog(oldSkillIds, newSkillIds) {
      const signSkillNames = []
      const outSkillNames = []
      const outSkillIds = []
      oldSkillIds.forEach(id => {
        if (!newSkillIds.includes(id)) {
          outSkillIds.push(id)
        }
      })
      for (const item of this.skillQueue) {
        const _id = this.$numToString(item.id)
        for (const id of newSkillIds) {
          if (id === _id) {
            signSkillNames.push(item.name)
          }
        }
        for (const id of outSkillIds) {
          if (id === _id) {
            outSkillNames.push(item.name)
          }
        }
      }
      if (signSkillNames.length > 0) {
        this.$callOperatorLogSuccess(10, signSkillNames.join(',')) // 签入技能成功
      }
      if (outSkillNames.length > 0) {
        this.$callOperatorLogSuccess(11, outSkillNames.join(',')) // 签出技能成功
      }
    }
  }
}
</script>
<style lang="scss" module>
@import "@/styles/mixin.scss";
.skill {
}
.btn{
  @include flex($justify: flex-end);
}
.btnSelect{
  padding: 10px 0 ;
}
</style>
